Day 1
Advanced Linux Commands, Piping, Redirection, and Bash Scripting
1.1 Advanced Linux Commands
These commands help automate tasks and manage system operations more efficiently.
-
grep: Search for patterns in files.
- Example:
grep "pattern" filename→ Finds the word "pattern" in the file.
- Example:
-
find: Locate files and directories.
- Example:
find /home -name "file.txt"→ Find file.txt in /home.
- Example:
-
tar: Archive and extract files.
- Example:
- Archive:
tar -cvf archive.tar file1 file2 - Extract:
tar -xvf archive.tar
- Archive:
- Example:
-
awk: Text processing in files.
- Example:
awk '{print $1}' file.txt→ Prints the first column.
- Example:
-
sed: Stream editor for text substitution.
- Example:
sed 's/old/new/' file.txt→ Replaces "old" with "new" in the file.
- Example:
-
top / htop: Display system processes.
- Use htop for a user-friendly, colorful interface.
1.2 Piping and Redirection
Piping (|)
Pass the output of one command as input to another.
- Example:
ls -l | grep ".txt"→ List only .txt files.
Redirection
Send output or input to/from files:
>: Overwrite output to a file- Example:
echo "Hello" > file.txt→ Writes "Hello" to file.txt.
- Example:
>>: Append output to a file- Example:
echo "World" >> file.txt→ Adds "World" to file.txt.
- Example:
<: Input redirection- Example:
sort < file.txt→ Sorts the contents of file.txt.
- Example:
1.3 Introduction to Bash Scripting
What is Bash Scripting?
Automating repetitive tasks in Linux. Bash scripts are sequences of Linux commands stored in a file.
Creating a Bash Script
- Open a file:
nano script.sh - Add the shebang:
#!/bin/bash
echo "Hello, World!" - Save and close the file.
- Make it executable:
chmod +x script.sh - Run the script:
./script.sh
Variables in Bash
#!/bin/bash
name="CyberTeam"
echo "Welcome to $name's Masterclass!"
Conditionals
#!/bin/bash
if [ -f "file.txt" ]; then
echo "File exists"
else
echo "File does not exist"
fi
Loops
#!/bin/bash
for i in {1..5}; do
echo "Number $i"
done